<template>
  <div>
    <a-form layout="vertical">
      <a-row v-if="isShowConfig2AppPage()" :gutter="16">
        <a-col :span="12">
          <a-form-item label="商户号：">
            <a-tag color="blue">{{ vdata.detailData.mchNo }}</a-tag>
          </a-form-item>
        </a-col>
      
        <a-col :span="24">
          <a-collapse v-model:activeKey="vdata.activeKey">
            <a-collapse-panel key="1" header="支付参数">
              <a-textarea
                v-model:value="vdata.detailData.succResParameter"
                disabled="disabled"
                style="height: 100px;color: black"
              />
            </a-collapse-panel>
          </a-collapse>
        </a-col>
        <a-divider />
        <a-col :span="24">
          <a-collapse v-model:activeKey="vdata.activeKey">
            <a-collapse-panel key="2" header="微信子商户号">
              <a-col :span="24">
                <a-form-item label="">
                  <a-textarea
                    v-model:value="vdata.originData"
                    disabled="disabled"
                    style="height: 100px;color: black"
                  />
                </a-form-item>
              </a-col>
            </a-collapse-panel>
          </a-collapse>
        </a-col>

        <a-divider />
        <a-col :span="24">
          <a-alert style="margin-bottom: 20px;" message="本页配置参数不做回显处理" type="info" />
        </a-col>
        <a-divider class="jeepay-m-divider" orientation="left"><a-tag color="black">应用配置</a-tag></a-divider>
        <a-col style="margin-top: 20px;" :span="isMobile ? 24 : 12">
          <a-form-item label="拉卡拉子商户号（merCupNo）">
            <a-input v-model:value.trim="vdata.lklSubMchInfo.merCupNo" class="form-item-content" />
          </a-form-item>
        </a-col>
        <a-col :span="isMobile ? 24 : 12">
          <a-form-item label="终端号（termNo）">
            <a-input v-model:value.trim="vdata.lklSubMchInfo.termNo" class="form-item-content" />
          </a-form-item>
        </a-col>
        <a-col :span="isMobile ? 24 : 12">
          <a-form-item label="微信子商户号（subMchId）">
            <a-input v-model:value.trim="vdata.lklSubMchInfo.subMchId" class="form-item-content" />
          </a-form-item>
        </a-col>
        
        <a-col :span="isMobile ? 24 : 16">
          <a-form-item label="请选择商户应用：">
            <a-select v-model:value="vdata.configAppId" class="form-item-content" placeholder="选择应用">
              <a-select-option key="">请选择商户应用</a-select-option>
              <a-select-option v-for="(item) in vdata.mchAppList" :key="item.appId">{{ item.appName }} [{{ item.appId }}]</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="isMobile ? 24 : 16">
          <a-popover placement="top">
            <a-button
              class="jeepay-m-btn"
              data-type="text"
              style="margin-right: 20px !important;"
              type="primary"
              :disabled="!vdata.configAppId"
              @click="configMchAppIdFunc"
            >
              <save-outlined />配置【支付参数】到应用
            </a-button>
            <a-button
              class="jeepay-m-btn"
              data-type="text"
              style="margin-right: 20px !important;"
              type="danger"
              :disabled="!vdata.configAppId"
              @click="configMchRateAppIdFunc"
            >
              <save-outlined />配置【费率】到应用
            </a-button>
          </a-popover>
          <a-button class="jeepay-m-btn" data-type="text" style="margin-right: 20px !important;" type="primary" @click="queryFunc"><bars-outlined />参数查询</a-button>
        </a-col>
      </a-row>
      <a-row>
        <a-divider class="jeepay-m-divider" orientation="left"><a-tag color="green">微信配置项</a-tag></a-divider>
        <a-col style="margin-top: 10px;" :span="isMobile ? 24 : 12">
          <a-form-item class="jeepay-valid" label="微信支付目录" style="margin: 0;">
            <a-input v-model:value.trim="vdata.configWxPayBaseUrl" class="form-item-content" />
            <a-button
              class="jeepay-m-btn"
              data-type="text"
              size="small"
              style="margin-left: 20px !important;"
              type="primary"
              @click="configInterfaceFunc('PAY_BASE_URL', vdata.configWxPayBaseUrl)"
            >
              <save-outlined />配置
            </a-button>
          </a-form-item>
        </a-col>
        <a-col :span="isMobile ? 24 : 12">
          <a-form-item class="jeepay-valid" label="关联服务商公众号appId：" style="margin: 0;">
            <a-input v-model:value.trim="vdata.configWxBindAppId" class="form-item-content" />
            <a-button
              class="jeepay-m-btn"
              data-type="text"
              size="small"
              style="margin-left: 20px !important;"
              type="primary"
              @click="configInterfaceFunc('BIND_APP_ID', vdata.configWxBindAppId)"
            >
              <save-outlined />配置
            </a-button>
          </a-form-item>
        </a-col>
        <a-col :span="isMobile ? 24 : 12">
          <a-form-item class="jeepay-valid" label="关联服务商小程序appId：" style="margin: 0;">
            <a-input v-model:value.trim="vdata.configWxBindLiteAppId" class="form-item-content" />
            <a-button
              class="jeepay-m-btn"
              data-type="text"
              size="small"
              style="margin-left: 20px !important;"
              type="primary"
              @click="configInterfaceFunc('BIND_APP_ID', vdata.configWxBindLiteAppId)"
            >
              <save-outlined />配置
            </a-button>
          </a-form-item>
        </a-col>
       
        <a-col :span="isMobile ? 24 : 12">
          <a-form-item class="jeepay-valid" label="关注appId：" style="margin: 0;">
            <a-input v-model:value.trim="vdata.configWxSubscribeAppId" class="form-item-content" />
            <a-button
              class="jeepay-m-btn"
              data-type="text"
              size="small"
              style="margin-left: 20px !important;"
              type="primary"
              @click="configInterfaceFunc('SUBSCRIBE_APP_ID', vdata.configWxSubscribeAppId)"
            >
              <save-outlined />配置
            </a-button>
          </a-form-item>
        </a-col>
      
        <a-col v-if="isShowConfig2AppPage()" :span="24">
          <div class="jeepay-m-pz">
            <a-popover placement="top">
              <template #title><span>一键配置微信配置项</span></template>
              <template #content>
                <p>顺序： 微信支付目录 --》 公众号AppId --> 小程序AppId --> 关注AppId </p>
                <p>提示： 若有异常则结束配置</p>
              </template>
              <a-button class="jeepay-m-btn" data-type="text" type="primary" @click="autoConfigFunc"><alert-outlined />一键配置微信配置项</a-button>
            </a-popover>
          </div>
        </a-col>

        <a-divider />
      </a-row>
    </a-form>
  </div>
</template>

<script lang="ts" setup>
import { API_URL_MCH_APPLYMENT_LIST, API_URL_MCH_APP, req, $applymentAppConfig, $lklApplymentAppConfig, $queryInterfaceConfig, $configInterfaceConfig, $getMchApplymentWxOpenInfo, $saveRateConfig } from '@/api/manage'
import {reactive, inject, getCurrentInstance} from 'vue'
const { $infoBox } = getCurrentInstance()!.appContext.config.globalProperties

// 参数注入： 是否手机端
let isMobile : any = inject('isMobile')
// 接收父组件的参数注入： 选择的商户应用
let appConfigModeByMchAppId : any = inject('appConfigModeByMchAppId')
// 接收父组件的参数注入： 选择的渠道
let appConfigModeBySelectedIfCode : any = inject('appConfigModeBySelectedIfCode')
// 接收父组件的参数注入： 配置方式 (判断是 运营平台  代理商 还是商户 )
let configMode : any = inject('configMode')

const vdata : any = reactive({
  detailData: {}, // 数据对象
  recordId: null, // 更新对象ID
  visible: false, // 是否显示弹层/抽屉
  mchAppList: [], // 商户app列表
  configAppId: '',
  
  configWxPayBaseUrl: '', // 微信支付目录
  configWxBindAppId: '', // 关联应用
  configWxBindLiteAppId: '', // 关联小程序
  configWxSubscribeAppId: '', // 关注公众号ID

  activeKey: '' , //手风琴展开key 
  mchShortName: '', //商户简称
  mchAppPublicKey: 'ISV', //商户应用key
  lklSubMchInfo: {},  // 拉卡拉子商户配置参数

})

function pageRender (recordId) { // 弹层打开事件

   //重置配置
  vdata.configAppId = ''
  vdata.mchAppList = []
  vdata.configWxPayBaseUrl = ''
  vdata.configWxBindAppId = ''
  vdata.configWxBindLiteAppId = ''
  vdata.configWxSubscribeAppId = ''
  vdata.mchShortName = ''
  vdata.mchAppPublicKey = 'ISV'

  vdata.activeKey = '' // 折叠

  vdata.recordId = recordId

  if (vdata.recordId) {
    req.getById(API_URL_MCH_APPLYMENT_LIST, recordId).then( (res) => {
      vdata.detailData = res
      if(vdata.detailData.succResParameter) {
        vdata.succParams = JSON.parse(vdata.detailData.succResParameter)
        vdata.lklSubMchInfo.merCupNo = vdata.succParams.merCupNo
        vdata.lklSubMchInfo.termNo = vdata.succParams.termNo
      }

      req.list(API_URL_MCH_APP, { pageSize: -1, mchNo: vdata.detailData.mchNo }).then(res2 => {
        vdata.mchAppList = res2.records
        if(vdata.mchAppList.length > 0){
          vdata.configAppId = vdata.mchAppList[0].appId
        }
      })

      $queryInterfaceConfig(recordId, null, null).then((res2) => {
        if (res2) {
          vdata.configWxPayBaseUrl = res2.paySiteUrl
          vdata.configWxBindAppId = res2.wxAppId
          vdata.configWxBindLiteAppId = res2.wxLiteAppId
          vdata.configWxSubscribeAppId = res2.wxAppId
        }
      })

      getMchApplymentWxOpenInfoFunc()

      vdata.visible = true
    })
  }else {
      // 查询配置信息 
      commonQueryInterfaceConfigFunc().then((res2) => {
        vdata.configWxPayBaseUrl = res2.paySiteUrl
        vdata.configWxBindAppId = res2.wxAppId
        vdata.configWxBindLiteAppId = res2.wxLiteAppId
        vdata.configWxSubscribeAppId = res2.wxAppId
      })
  }

}

// 配置本系统的app应用配置项
function configMchAppIdFunc(){

  // 如果进件记录不为空，则为进件页面参数配置逻辑；否则为应用配置逻辑
  if (vdata.recordId) {
    if(!vdata.configAppId){
      $infoBox.message.error('请选择商户应用')
      return Promise.reject()
    }

    if(!vdata.lklSubMchInfo.merCupNo || !vdata.lklSubMchInfo.termNo || !vdata.lklSubMchInfo.subMchId) {
      $infoBox.message.error('请填写完整配置参数：拉卡拉子商户号、终端号、微信子商户号。')
      return Promise.reject()
    }

    return $lklApplymentAppConfig(vdata.recordId, vdata.configAppId, vdata.lklSubMchInfo).then((res) => {
      $infoBox.message.success('商户应用配置完成， 如商户支付方式未配置，请进行方式配置。 ')
      return Promise.resolve()
    })
  }else {
    return $applymentAppConfig(appConfigModeByMchAppId, appConfigModeByMchAppId).then((res) => {
      $infoBox.message.success('商户应用配置完成， 如商户支付方式未配置，请进行方式配置。 ')
      return Promise.resolve()
    })
  }

}


// 配置接口相关配置信息
function configInterfaceFunc(configType, configVal){

  if(!configVal){
    $infoBox.message.error('请填写对应参数值!')
    return Promise.reject()
  }

  // 默认为进件记录ID、商户应用appId
  let recordId = vdata.recordId
  let configAppId = vdata.configAppId
  // 默认为空
  let appConfigModeAndIfCode = ''
  // 当进件记录ID为空时取透传的商户应用appId；类型默认为当前ifcode
  if (!recordId) {
    appConfigModeAndIfCode = appConfigModeBySelectedIfCode
    
    recordId = appConfigModeByMchAppId
    configAppId = appConfigModeByMchAppId
  }else{
    if(!vdata.configAppId){
      $infoBox.message.error('请选择商户应用')
      return Promise.reject()
    }
  }
  
  return $configInterfaceConfig(recordId, configAppId, configType, configVal, appConfigModeAndIfCode).then((res) => {
      
      if(res.channelState == 'CONFIRM_SUCCESS'){
         $infoBox.message.success('配置完成')
        return Promise.resolve()
      }

      $infoBox.modalError('接口配置失败：' + '[' + res.channelErrCode + ']' + res.channelErrMsg)
      return Promise.reject()
  })

}

// 一键配置 ( 顺序 --》 先配置本系统的商户应用参数信息 --》 接口侧的 支付目录  --》 appId --> 小程序appId  --> 关注公众号  )【若有报错则停止执行】
// async await  其实就是 Prosise的语法糖。 只有then才会进入下一个 await
async function autoConfigFunc(){

  await configMchAppIdFunc()

  if(vdata.configWxPayBaseUrl){
    await configInterfaceFunc('PAY_BASE_URL', vdata.configWxPayBaseUrl)
  }

  if(vdata.configWxBindAppId){
    await configInterfaceFunc('BIND_APP_ID', vdata.configWxBindAppId)
  }

  if(vdata.configWxBindLiteAppId){
    await configInterfaceFunc('BIND_APP_ID', vdata.configWxBindLiteAppId)
  }

  if(vdata.configWxSubscribeAppId){
    await configInterfaceFunc('SUBSCRIBE_APP_ID', vdata.configWxSubscribeAppId)
  }

}


function queryFunc(){

  if(!vdata.configAppId){
    $infoBox.message.error('请选择商户应用')
    return Promise.reject()
  }

  return $configInterfaceConfig(vdata.recordId, vdata.configAppId, 'QUERY', '1', null).then((res) => {
    vdata.lklSubMchInfo = JSON.parse(res)
    $infoBox.modalSuccess('查询结果：', res)
  })

}

function onClose () {
  vdata.visible = false
}

// 微信实名认证查询
function getMchApplymentWxOpenInfoFunc(){
  $getMchApplymentWxOpenInfo(vdata.recordId).then(res => {
      if(res && res.originData) {
          vdata.originData = res.originData
          vdata.lklSubMchInfo.subMchId = res.originData
      }
  }).finally(() => {
  })
}

// 配置费率到应用
function configMchRateAppIdFunc(){

  if(!vdata.configAppId){
    $infoBox.message.error('请选择商户应用')
    return Promise.reject()
  }

  // 请求对象
  let configMode = 'mgrMch' // 运营平台配置商户费率
  let reqObject = {infoId: vdata.configAppId, ifCode: vdata.detailData.ifCode, configMode: configMode, MCHRATE: JSON.parse(vdata.detailData.applyDetailInfo).paywayFeeList}
  return $saveRateConfig(reqObject).then((res) => {
    $infoBox.message.success('费率保存成功')
  })

}

// 给diy页面的全局公用函数 （ 请求在一个地方处理 ）
function commonQueryInterfaceConfigFunc(){

  // 查询配置信息参数。 
  let reqApplyId = vdata.recordId
  let applyIdConvertMchAppId = 0
  let convertMchAppIfCode :any = null

  // 应用配置页面 需要做转换
  reqApplyId = appConfigModeByMchAppId
  applyIdConvertMchAppId = 1
  convertMchAppIfCode = 'lklpay'

  // 查询配置信息 
  return $queryInterfaceConfig(reqApplyId, applyIdConvertMchAppId, convertMchAppIfCode)

}

// 是否 显示 配置到应用的选项。 
function isShowConfig2AppPage(){

  // 运营平台 --》 商户应用配置 此时：  无需显示配置到应用即可。 
  if(configMode == 'mgrMch' && appConfigModeByMchAppId){
    return false
  }

  return true

}

defineExpose({ pageRender })
</script>
<style scoped>

.form-item-content{
  width: 70%
}

</style>